package org.sample.springbootasync.service;

import java.net.URI;
import java.util.concurrent.Future;

import org.sample.springbootcommon.model.DateTimeRequest;
import org.sample.springbootcommon.model.DateTimeResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class DateTimeService {

	@Autowired
	private RestTemplate restTemplate;

	public DateTimeResponse get() {

		URI url = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/mock/datetime").build().toUri();
		ResponseEntity<DateTimeResponse> responseEntity = restTemplate.getForEntity(url, DateTimeResponse.class);
		return responseEntity.getBody();
	}

	@Async
	public Future<DateTimeResponse> asyncGet() {
		return new AsyncResult<>(get());
	}

	public DateTimeResponse post(DateTimeRequest request) {

		URI url = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/mock/datetime").build().toUri();
		ResponseEntity<DateTimeResponse> responseEntity = restTemplate.postForEntity(url, request,
				DateTimeResponse.class);
		return responseEntity.getBody();
	}

	@Async
	public Future<DateTimeResponse> asyncPost(DateTimeRequest request) {
		return new AsyncResult<>(post(request));
	}

}
